package client

import (
	"common/initialization"
	"context"
	"fmt"
	"google.golang.org/grpc"
	order "order_srv/proto"
)

type OrderHandler func(ctx context.Context, client order.OrderClient) (interface{}, error)

func OrderClient(ctx context.Context, handler OrderHandler) (interface{}, error) {
	cf := initialization.Config.OrderServer
	dial, err := grpc.Dial(fmt.Sprintf("%s:%d", cf.Hort, cf.Port), grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := order.NewOrderClient(dial)
	return handler(ctx, client)
}
func OrderAdd(ctx context.Context, req *order.OrderAddRequest) (*order.OrderAddResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, client order.OrderClient) (interface{}, error) {
		add, err := client.OrderAdd(ctx, req)
		if err != nil {
			return nil, err
		}
		return add, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.OrderAddResponse), nil
}
func UpdateOrderStatus(ctx context.Context, req *order.UpdateOrderStatusRequest) (*order.UpdateOrderStatusResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, client order.OrderClient) (interface{}, error) {
		add, err := client.UpdateOrderStatus(ctx, req)
		if err != nil {
			return nil, err
		}
		return add, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.UpdateOrderStatusResponse), nil
}
